/*
 * HttpMessage.cpp
 *
 *  Created on: 2018年7月3日
 *      Author: zhengboyuan
 */

#include "HttpMessage.h"
#include "TStringUtil.h"


HttpMessage::HttpMessage():
        m_line(),
        m_header(),
        m_body(),
        m_version("HTTP/1.1"),
        m_method(),
        m_url(),
        m_status(),
        m_reason()
{

}

HttpMessage::~HttpMessage()
{
}

int32_t HttpMessage::getContentLength() const
{
    std::string value;
    getHeader("Content-Length", value);
    int32_t length = 0;
    comn::StringCast::toValue(value, length);
    return length;
}

bool HttpMessage::getContentType(std::string& name) const
{
    return getHeader("Content-Type", name);
}

void HttpMessage::clear()
{
    m_line.clear();
    m_header.clear();
    m_body.clear();

    m_method.clear();
    m_url.clear();
    m_urlPath.clear();

    m_status = 0;
    m_reason.clear();
}


bool HttpMessage::isRequest() const
{
    return (m_url.size() > 0);
}

bool HttpMessage::isResponse() const
{
    return (m_url.empty());
}


// request
const std::string& HttpMessage::getUrl() const
{
    return m_url;
}

const std::string& HttpMessage::getUrlPath() const
{
    return m_urlPath;
}

const std::string& HttpMessage::getMethod() const
{
    return m_method;
}


int HttpMessage::getStatus() const
{
    return m_status;
}

const std::string& HttpMessage::getReason() const
{
    return m_reason;
}

bool HttpMessage::getHeader(const std::string& name, std::string& value) const
{
    bool found = false;
    Headers_t::const_iterator it = m_header.find(name);
    if (it != m_header.end())
    {
        value = it->second;
        found = true;
    }
    return found;
}

bool HttpMessage::hasHeader(const std::string& name) const
{
    bool found = false;
    Headers_t::const_iterator it = m_header.find(name);
    if (it != m_header.end())
    {
        found = true;
    }
    return found;
}

bool HttpMessage::igetHeader(const std::string& name, std::string& value) const
{
    bool found = false;
    Headers_t::const_iterator it = ifindHeader(name);
    if (it != m_header.end())
    {
        value = it->second;
        found = true;
    }
    return found;
}

bool HttpMessage::ihasHeader(const std::string& name) const
{
    bool found = false;
    Headers_t::const_iterator it = ifindHeader(name);
    if (it != m_header.end())
    {
        found = true;
    }
    return found;
}

Headers_t::const_iterator HttpMessage::ifindHeader(const std::string& name) const
{
    Headers_t::const_iterator it = m_header.begin();
    for (; it != m_header.end(); ++ it)
    {
        if (comn::StringUtil::icompare(name, it->first) == 0)
        {
            break;
        }
    }
    return it;
}
